from flask import request, Blueprint,render_template, redirect, url_for
from datetime import datetime
from models import MonthlyBudget, Expense, db
from decimal import Decimal

expenses_bp = Blueprint('expenses', __name__, url_prefix='/expenses')

@expenses_bp.route("/", methods=["GET", "POST"])
def expenses():
    if request.method == "POST":
        try:
            # 获取表单数据
            amount_str = request.form.get("amount")
            date_str = request.form.get("date")
            description = request.form.get("description", "")

            # 如果没有提供金额
            if not amount_str:
                return "缺少必填字段: 金额", 400

            # 如果没有提供日期，使用当前日期
            if not date_str:
                date = datetime.now().date()
            else:
                try:
                    date = datetime.strptime(date_str, "%Y-%m-%d").date()
                except ValueError:
                    return f"无效的日期格式: {date_str}", 400

            # 尝试将金额转换为Decimal
            try:
                amount = Decimal(amount_str).quantize(Decimal('0.00'))
                if amount <= 0:
                    raise ValueError("金额必须大于0")
            except ValueError:
                return f"无效的金额格式: {amount_str}", 400

            month = date.month
            year = date.year

            # 创建新支出
            new_expense = Expense(
                amount=amount,
                date=date,
                month=month,
                year=year,
                description=description,
            )

            # 检查并创建预算记录
            budget = MonthlyBudget.query.filter_by(month=month, year=year).first()

            if not budget:
                # 如果预算不存在，创建一个新的预算记录，预算为0
                new_budget = MonthlyBudget(
                    month=month,
                    year=year,
                    budget=Decimal('0.00'),
                    remaining=-amount,  # 初始就超支
                )
                db.session.add(new_budget)
            else:
                # 更新月度预算（允许为负数）
                budget.remaining = (Decimal(str(budget.remaining)) - amount).quantize(Decimal('0.00'))

            db.session.add(new_expense)
            db.session.commit()

            return redirect(url_for("expenses.expenses"))

        except Exception as e:
            db.session.rollback()
            return "处理请求时发生意外错误，请联系技术支持", 500

    # 获取今天的日期作为默认值
    today = datetime.now().strftime("%Y-%m-%d")

    # 获取所有支出记录
    all_expenses = Expense.query.all()  # 查询所有支出

    return render_template(
        "expenses.html",
        today=today,
        expenses=all_expenses,
    )  # 将所有支出传递给模板


@expenses_bp.route("/delete/<int:expense_id>", methods=["POST"])
def delete(expense_id):
    try:
        expense = Expense.query.get_or_404(expense_id)
        db.session.delete(expense)
        db.session.commit()
        return redirect(url_for("expenses.expenses"))
    except Exception as e:
        # 回滚更改
        db.session.rollback()
        # 返回错误信息
        return f"删除支出时出错: {str(e)}", 500

@expenses_bp.route("/api/monthly-stats")
def get_monthly_stats():
    # 获取当前日期
    now = datetime.now()
    current_month = now.month
    current_year = now.year

    # 计算本月总支出
    total_expense_result = (
        db.session.query(db.func.sum(Expense.amount))
        .filter(Expense.month == current_month, Expense.year == current_year)
        .scalar()
    )
    
    total_expense = Decimal(str(total_expense_result)).quantize(Decimal('0.00')) if total_expense_result else Decimal('0.00')

    # 获取本月预算剩余
    monthly_budgets = MonthlyBudget.query.filter_by(
        month=current_month, year=current_year
    ).all()

    #sum() 函数会返回整数 0，而不是 Decimal 对象
    remaining_budget = Decimal('0.00')
    for budget in monthly_budgets:
        remaining_budget += Decimal(str(budget.remaining))
    remaining_budget = remaining_budget.quantize(Decimal('0.00'))

    return {"totalExpense": str(total_expense), "remainingBudget": str(remaining_budget)}